package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<Permission> listAll() {
        List<Permission> permissions = permissionMapper.selectAll();
        return permissions;
    }
    @Override
    public PageInfo<Permission> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Permission> permissions = permissionMapper.selectForList(qo);
        return new PageInfo<>(permissions);
    }

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    @Override
    public void reload() {
        //查出数据库中所有的权限
        List<String> expressions = permissionMapper.ListExpression();
        //通过RequestMappingHandlerMapping对象(springmvc的处理器映射器)获取每个控制器中带RequestMapping注解的方法
        //即获取所有请求方法
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        Collection<HandlerMethod> values = handlerMethods.values();
        for (HandlerMethod value : values) {
            RequiredPermission methodAnnotation = value.getMethodAnnotation(RequiredPermission.class);
            if(methodAnnotation==null){
                continue;
            }
            String name = methodAnnotation.name();
            String expression = methodAnnotation.expression();
            if(!expressions.contains(expression)){
                Permission permission = new Permission();
                permission.setName(name);
                permission.setExpression(expression);
                permissionMapper.insert(permission);
                expressions.add(expression);
            }
        }
    }
}
